<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索 -->
      <el-form :inline="true" :model="listQuery" size="small">
        <el-row>
          <el-col :span="30">
            <el-form-item>
              <el-input
                placeholder="请输入工程名称/档案号"
                clearable
                v-model="listQuery.name"
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                size="small"
                v-model="listQuery.search_date"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="请输入工程造价"
                v-model="listQuery.costs"
                class="pre-select"
                @input="listQuery.costs = listQuery.costs.replace(/[^\d]/g, '')"
              >
                <el-select
                  v-model="listQuery.operator"
                  slot="prepend"
                  placeholder="请选择"
                >
                  <el-option label="大于" value="1"></el-option>
                  <el-option label="小于" value="0"></el-option>
                </el-select>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="getArchiveList"
              >
                查询
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item>
              <el-select
                size="small"
                v-model="listQuery.category"
                clearable
                placeholder="请选择工程类型"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="请输入二级建造师"
                clearable
                v-model="listQuery.architect"
              />
            </el-form-item>
            <el-form-item label="" prop="is_bid">
              <el-select
                v-model="listQuery.is_bid"
                clearable
                placeholder="请选择是否完结"
              >
                <el-option
                  v-for="item in is_bid"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <!-- <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
              >
                新增{{ title }}
              </el-button>
            </el-form-item> -->
          </el-col>
        </el-row>
      </el-form>
      <!-- 列表 -->
      <el-table
        style="width: 100%"
        v-loading="listLoading"
        border
        fit
        stripe
        highlight-current-row
        size="small"
        :data="datas"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column label="#" align="center" type="index" width="50">
        </el-table-column>
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.documents"
              border
              v-if="scope.row.documents.length > 0"
              size="mini"
            >
              <el-table-column
                align="center"
                label="资料类型"
                prop="doc_type_name"
                width="200"
              />
              <el-table-column label="文件名称" prop="name">
                <template slot-scope="docs">
                  <el-link :href="docs.row.content">{{
                    docs.row.name
                  }}</el-link>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="200px">
                <template slot-scope="docs">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    circle
                    @click="handleItemDelete(docs, scope.row.documents)"
                  >
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column
          v-for="column in tableColumns"
          :label="column.title"
          :prop="column.key"
          :key="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
            >
            </el-button>
            <el-button
              type="success"
              icon="el-icon-upload"
              size="mini"
              @click="handleUpload(scope)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getArchiveList"
      />
      <!-- 分页 end -->
    </el-card>

    <!-- 对话框 -->
    <el-dialog :title="getTitle" :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="工程名称" prop="project">
              <el-select
                v-model="form.project"
                clearable
                placeholder="请选择工程名称"
              >
                <el-option
                  v-for="item in projects"
                  :key="item.value"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="档案号" prop="code">
              <el-input v-model="form.code" placeholder="档案号" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="建档时间" prop="archive_date">
              <el-date-picker
                v-model="form.archive_date"
                type="date"
                placeholder="建档时间"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程类型" prop="category">
              <el-select
                v-model="form.category"
                clearable
                placeholder="请选择工程类型"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工程造价" prop="costs">
              <el-input
                v-model="form.costs"
                placeholder="工程造价"
                clearable
                @input="form.costs = form.costs.replace(/[^\d.]/g, '')"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="duty_man">
              <el-input
                v-model="form.duty_man"
                placeholder="负责人"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否投标" prop="is_bid">
              <el-select
                v-model="form.is_bid"
                clearable
                placeholder="请选择是否完结"
              >
                <el-option
                  v-for="item in is_bid"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否完结" prop="finish">
              <el-select
                v-model="form.finish"
                clearable
                placeholder="请选择是否完结"
              >
                <el-option
                  v-for="item in finish"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table
          style="width: 100%; margin-top: 30px"
          border
          highlight-current-row
          size="small"
          :data="documents"
        >
          <el-table-column label="#" align="center" type="index">
          </el-table-column>
          <el-table-column
            label="资料类型"
            prop="doc_type_name"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            label="文档"
            prop="name"
            header-align="center"
            align="left"
          >
            <template slot-scope="scope">
              <el-link :href="scope.row.content">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80px">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
                @click="handleItemDelete(scope)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSave(false)" size="small"
          >保存</el-button
        >
        <el-button type="success" @click="handleSave(true)" size="small"
          >保存并上传文件</el-button
        >
      </span>
    </el-dialog>
    <!-- 上传文件弹框 -->
    <el-dialog
      title="文档资料上传"
      :visible.sync="uploadDlgVisible"
      width="50%"
    >
      <el-form
        :model="uploadForm"
        ref="uploadFormRef"
        size="small"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="档案号">
              <el-input v-model="form.code" placeholder="" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程名称">
              <el-input
                v-model="form.project_name"
                placeholder=""
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item prop="doc_type" label="资料类型">
          <el-select
            v-model="uploadForm.doc_type"
            placeholder="资料类型"
            clearable=""
          >
            <el-option
              v-for="item in docTypes"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文档" prop="content">
          <el-upload
            ref="upload"
            name="content"
            action="/api/building/file_upload/"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            multiple
            :file-list="uploadForm.fileList"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.rar,.zip,.PDF,.DOC,.DOCX,.XLS,.XLSX,.RAR,.ZIP, .jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-table
          style="width: 100%; margin-top: 30px"
          border
          highlight-current-row
          size="small"
          :data="documents"
        >
          <el-table-column label="#" align="center" type="index">
          </el-table-column>
          <el-table-column
            label="资料类型"
            prop="doc_type_name"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            label="文档"
            prop="name"
            header-align="center"
            align="left"
          >
            <template slot-scope="scope">
              <el-link :href="scope.row.content">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80px">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
                @click="handleItemDelete(scope)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDlgVisible = false" size="small"
          >关闭</el-button
        >
      </span>
    </el-dialog>
    <!-- 上传文件弹框  end-->
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { mapGetters } from "vuex";
import { toThousandFilter } from "@/filters";
import {
  getArchives,
  addArchive,
  delArchive,
  getArchiveById,
  updateArchive,
  fileUpload,
  getProjectList,
  getDocTypes,
  getDocumentsByArchiveId,
  delDocument,
  getCategory_list,
} from "@/api/building";

const defaultForm = {
  code: "",
  project: null,
  project_name: null,
  is_bid: null,
  costs: 0,
  category: null,
  duty_man: "",
  finish: null,
  user: null,
  documents: [],
};
const defUploadForm = {
  archive_id: null,
  doc_type: null,
  content: null,
  fileList: [],
};

export default {
  name: "Archive",
  data() {
    return {
      select: "",
      title: "工程档案",
      form: Object.assign({}, defaultForm),
      uploadForm: Object.assign({}, defUploadForm),
      projectName: "",
      formRules: {
        code: [{ required: true, message: "请输入档案号", trigger: "blur" }],

        project: [
          { required: true, message: "请选择工程项目", trigger: "blur" },
        ],

        archive_date: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],

        // is_bid: [
        //   { required: true, message: "请输入是否投标", trigger: "blur" },
        // ],

        // costs: [{ required: true, message: "请输入工程造价", trigger: "blur" }],
        // duty_man: [
        //   { required: true, message: "请输入负责人", trigger: "blur" },
        // ],
        // finish: [
        //   { required: true, message: "请输入是否完结", trigger: "blur" },
        // ],
      },
      total: 0,
      datas: [],
      projects: [],
      docTypes: [],
      documents: [],
      categoryList: [],
      listLoading: true,
      fileList: [],
      edit: false,
      dialogVisible: false,
      uploadDlgVisible: false,
      listQuery: {
        page: 1,
        page_size: 20,
        search_date: null,
        name: null,
        costs: null,
        category: null,
        is_bid: null,
        architect: null,
        operator: null,
      },

      finish: [
        { value: 0, label: "未完" },
        { value: 1, label: "完结" },
      ],
      is_bid: [
        { value: 0, label: "否" },
        { value: 1, label: "是" },
      ],

      tableColumns: [
        {
          key: "code",
          title: "档案号",
          align: "center",
          width: "100px",
        },
        {
          key: "project_name",
          title: "工程名称",
          align: "left",
        },
        {
          key: "archive_date",
          title: "建档日期",
          align: "center",
          width: "90px",
        },
        {
          key: "category_name",
          title: "工程类型",
          align: "center",
          width: "90px",
        },
        {
          key: "architect",
          title: "二级建造师",
          align: "center",
          width: "100px",
        },
        {
          key: "is_bid_name",
          title: "是否投标",
          align: "center",
          width: "90px",
        },
        {
          key: "costs",
          title: "工程造价(元)",
          align: "center",
          width: "120px",
        },
        {
          key: "duty_man",
          title: "负责人",
          align: "center",
          width: "100px",
        },
        {
          key: "finish_name",
          title: "是否完结",
          align: "center",
          width: "100px",
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  components: {
    Pagination,
  },
  computed: {
    ...mapGetters(["uid", "token"]),
    getTitle() {
      return this.edit ? `修改${this.title}` : `增加${this.title}`;
    },
    headerObj() {
      return {
        authorization: "JWT " + this.token,
      };
    },
    uploadData() {
      return {
        archive_id: this.uploadForm.archive_id,
        doc_type_id: this.uploadForm.doc_type,
      };
    },
  },
  created() {
    this.getArchiveList();
    this.getAllProject();
    this.getDocTypeList();
    this.getCategory();
  },
  methods: {
    handleRemove() {},
    //上传前
    handleBeforeUpload(file) {
      if (this.uploadForm.doc_type == null) {
        this.$message.error("请选择资料类型");
        return false;
      }
      const flag = file.size / 1024 / 1024 < 10;
      if (!flag) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return flag;
    },
    handleSuccess(res, file, filelist) {
      console.log(res);
      this.documents.push(res.file);
    },
    //删除项(文档资料)
    handleItemDelete({ $index, row }, documents) {
      this.$confirm("确定要删除此文档资料吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delDocument(row.id);
          if (documents) {
            documents.splice($index, 1);
          } else {
            this.documents.splice($index, 1);
          }

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    //获取工程类型数据列表
    getCategory() {
      getCategory_list()
        .then((res) => {
          if (res) {
            this.categoryList = res;
          }
        })
        .catch((error) => {
          console.log(error.message);
        });
    },

    getDocumentsByArchive(id) {
      const params = {
        archive_id: id,
      };
      getDocumentsByArchiveId(params)
        .then((res) => {
          console.log(res);
          this.documents = res;
        })
        .catch((error) => {
          this.$message.error("获取文档列表失败!");
        });
    },
    getArchiveList() {
      this.listLoading = true;
      getArchives(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败!");
        });
    },
    //获取工程名称数据
    getAllProject() {
      getProjectList()
        .then((res) => {
          this.projects = res;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //获取标书类型数据列表
    getDocTypeList() {
      getDocTypes()
        .then((res) => {
          this.docTypes = res;
        })
        .catch((error) => {
          console.log(error.message);
        });
    },
    handleUpload(scope) {
      this.form = scope.row;
      this.documents = scope.row.documents;
      this.uploadForm = Object.assign({}, defUploadForm);
      this.uploadForm.archive_id = scope.row.id;
      this.uploadDlgVisible = true;
    },
    //添加数据,弹框显示
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.documents = [];
      this.edit = false;
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = scope.row;
      this.documents = scope.row.documents;

      this.edit = true;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;
        if (this.edit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateArchive(this.form);
          const index = this.datas.findIndex((v) => v.id === res.id);
          this.datas.splice(index, 1, res);
        } else {
          this.form.user = this.uid;
          res = await addArchive(this.form);
          const { id } = res;
          if (id > 0) {
            this.form = res;
            this.datas.unshift(res);
          }
        }

        // this.getArchiveList();

        const { code, project_name, costs, duty_man } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>档案号: ${code}</div>
              <div>工程名称: ${project_name}</div>
              <div>工程造价: ${costs}</div>
              <div>负责人: ${duty_man}</div>
            `,
          type: "success",
        });
        if (flag) {
          ///弹出上传文件窗口
          this.uploadDlgVisible = true;

          //工程档案ID赋值
          this.uploadForm = Object.assign({}, defUploadForm);
          this.uploadForm.archive_id = res.id;
          this.documents = res.documents;
          this.$nextTick(() => {
            this.dialogVisible = false;
            this.$refs.upload.clearFiles();
          });
        } else {
          this.dialogVisible = false;
        }
      });
    },

    // //限制输入框只能输入数字
    number() {
      this.defaultForm.costs = this.defaultForm.costs.replace(/[^\d.]/g, "");
    },

    //删除工程档案数据
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delArchive(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    dataFormatter(row, column, cellValue, index) {
      if (column.property == "costs") {
        return cellValue && toThousandFilter(cellValue.toFixed(2));
      } else {
        return cellValue;
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "costs") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] = toThousandFilter(sums[index]);
          sums[index] += " 元";
        } else {
          return;
        }
      });

      return sums;
    },
  },
};
</script>

<style lang="scss" scoped>
.item {
  margin-top: 8px;
}
</style>